package edu.tum.cs.stageflow.benchmarkapplications.sobelfilter;

import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.util.LinkedList;

import javax.imageio.ImageIO;


public class LinearSobelFilter {
	private static final String DIR_BENCHMARK_RESULTS = "C:/StageFlowTestDir/benchmarkresults/";

	public class TimingResult {
		private long startTime = 0;
		private long stopTime = 0;
		public long getStartTime() {
			return startTime;
		}
		public void setStartTime(long startTime) {
			this.startTime = startTime;
		}
		public long getStopTime() {
			return stopTime;
		}
		public void setStopTime(long stopTime) {
			this.stopTime = stopTime;
		}
		
	}
	
	public static void main(String[] args) {
		String inputPath = "C:/StageFlowTestDir/orig";
		String outputPath = "C:/StageFlowTestDir/sobeled/";
		File file = new File(inputPath);
		int writtenFileCounter = 0;
		
		LinearSobelFilter linSobFil = new LinearSobelFilter();
		LinkedList<TimingResult> timingResults = new LinkedList<TimingResult>();
		TimingResult totalTime = linSobFil.new TimingResult();
		totalTime.setStartTime(System.nanoTime());
		
		if (file.isDirectory() && file.listFiles().length > 0) {
			for(File f : file.listFiles()) {
				TimingResult tempTime = linSobFil.new TimingResult();
				tempTime.setStartTime(System.nanoTime());
				BufferedImage image, result;
				try {
					image = ImageIO.read(f);
				} catch (IOException e) {
					return;
				}
				
				SmartSobelFilter filter = new SmartSobelFilter();
				result = filter.filter(image);
				try {
					ImageIO.write(result, "jpg", new File(outputPath + "_pic_" +writtenFileCounter+".jpg"));
				} catch (IOException e) {
					//TODO failed
				}
				writtenFileCounter++;
				tempTime.setStopTime(System.nanoTime());
				timingResults.add(tempTime);
			}
		}
		totalTime.setStopTime(System.nanoTime());
		String result = "Benchmark Result for ;;;;;;;; LinearSobelFilter\n";
		result += "Start Time; Stop Time;";
		result += totalTime.getStartTime() + ";" + totalTime.getStopTime() + "\n\n";
		for(TimingResult tr : timingResults) {
			result += tr.getStartTime() + ";" + tr.getStopTime() + "\n";
		}
		
		String german_result = result.replace(".", ",");
		
		try {
			PrintWriter writer = new PrintWriter(DIR_BENCHMARK_RESULTS
					+ "LinearSobelFilter.csv", "UTF-8");
			writer.print(german_result);
			writer.close();
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (UnsupportedEncodingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
}
